<?php

namespace App\Http\Requests;

use App\Models\ProductSku;
use App\Models\UserAddress;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class OrderRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [

            /* 写法一
            'address_id'     => [
                'required',
                Rule::exists('user_addresses', 'id')->where('user_id', $this->user()->id),
            ],
            //*/

            // 写法二（最简写法）
            'address_id'=>'required|exists:user_addresses,id,user_id,'.$this->user()->id,

            /* 写法三
            'address_id'=>[
                'required',
                function($attribute, $value, $fail){
                    // 在当前用户的地址列表里面查找 id 等于 $value 的地址
                    if(!$this->user()->addresses()->find($value))
                        $fail('地址不存在');
                }
            ],
            //*/
            'items'=>'required|array',
            'items.*.amount'=>'required|integer|min:1',
            'items.*.sku_id'=>[
                'required',
                function($attribute, $value, $fail){
                    if(!$sku=ProductSku::find($value))
                        $fail('商品规格不存在');
                    else if(!$sku->product->on_sale)
                        $fail('商品已下架');
                    else if($sku->stock===0)
                        $fail('商品已售罄');
                    else{
                        preg_match('/items.(\d)+.sku_id/', $attribute, $arr);
                        $amount=$this->input('items')[$arr[1]]['amount'];
                        if($sku->stock < $amount)
                            $fail($sku->product->title.'库存不足');
                    }
                }
            ],
        ];
    }

    public function attributes(){
        return [
            'address_id'=>'用户地址',
            'items'=>'提交的商品信息',
            'items.*.amount'=>'商品数量',
        ];
    }
}
